package mymyoux.io.sockets.clients
{
	import flash.utils.ByteArray;
	
	import mymyoux.debug.log;
	import mymyoux.io.sockets.clients.clientsClasses.MBinarySocket;
	import mymyoux.io.sockets.clients.clientsClasses.MRoom;
	import mymyoux.io.sockets.clients.clientsClasses.MSocketsArray;
	import mymyoux.io.sockets.mapping.Telegramme;
	import mymyoux.signals.MetaSignal;
	import mymyoux.signals.Signal;
	import mymyoux.utils.Hash;

	public class MClient
	{
		protected var _id:uint;
		protected var _sockets:MSocketsArray;
		protected var _rooms:Hash;
		protected var socket:MBinarySocket;
		protected var signals:MetaSignal;
		//TODO: premier host et port = point d'entrée
		//TODO: temporiser write
		public function MClient(host:String, port:uint, id:uint)
		{
			_id = id;
			_rooms = new Hash();
			_sockets = new MSocketsArray(_id);
			socket = new MBinarySocket(_id);
			socket.host = host;
			socket.port = port;
			socket.signalStatus.add(onStatus, socket);
			
			_sockets.put(host, port, socket);
		/*	socket = new BinarySocket();
			socket.signalData.add(onSocketData);*/
			//signals = new MetaSignal(String, Object);
			signals = new MetaSignal(Object);
		}
		protected function onStatus(connected:Boolean, socket:MBinarySocket):void
		{
			trace("Connected="+connected+" from client:"+socket);
		}
		public function getRoom(name:String):MRoom
		{
			var room:MRoom;
			if(!_rooms.has(name))
			{
				room = new MRoom(name);
				room.socket = _sockets.first;
				_rooms.put(name, room);
			}
			return _rooms.get(name) as MRoom;
		}
		public function get signal():MetaSignal
		{
			return signals;
		}
		public function set host(value:String):void
		{
			socket.host = value;
		}
		public function get host():String
		{
			return socket.host;
		}
		public function connect():void
		{
			socket.connect();
		}
		public function set port(value:uint):void
		{
			socket.port = value;
		}
		protected function onSocketData(socket:BinarySocket, byteArray:ByteArray):void
		{
			log("MClient data:["+byteArray+"]");
			try
			{
				var telegramme:Telegramme = byteArray.readObject() as Telegramme;
				trace("telegramme:"+telegramme.read());
				trace("test:"+telegramme.read());
				//trace(telegramme.read() is String);
				signals.dispatch(telegramme.action, telegramme.read() as Object);
			}catch(error:Error)
			{
				log("Error MClient:onSocketData:["+byteArray+"]:"+error);
			}
		}
		public function get port():uint
		{
			return socket.port;
		}
		public function write(action:String, data:Object):void
		{
			var telegramme:Telegramme = new Telegramme();
			telegramme.action = action;
			telegramme.command = Telegramme.SEND;
			telegramme.write(data);
			socket.write(telegramme);
		}
	}
}